-module (gen_herd_test_task).

-export ([ start/2,
           finish_init/2 ]).

-behaviour (gen_server).
-export ([ init/1,
           handle_call/3,
           handle_cast/2,
           handle_info/2,
           terminate/2,
           code_change/3 ]).

-record (testtask, { partition, offset, finished = false }).

%-=====================================================================-
%-                                Public                               -
%-=====================================================================-

start (Partition, Offset) ->
  gen_server:start (?MODULE, [ Partition, Offset ], []).

finish_init (ServerRef, Group) ->
  gen_server:call (ServerRef, { finish_init, Group }).

%-=====================================================================-
%-                         gen_server callbacks                        -
%-=====================================================================-

init ([ Partition, Offset ]) ->
  process_flag (trap_exit, true),
  { ok, #testtask{ partition = Partition, offset = Offset } }.

handle_call ({ finish_init, _Group }, _From, State) ->
  { reply, ok, State#testtask{ finished = true } };
handle_call (get_value, _From, State = #testtask{ finished = true }) ->
  { reply, State#testtask.partition + State#testtask.offset, State }.

handle_cast (_Msg, State) ->
  { noreply, State }.

handle_info ({ 'EXIT', _Pid, Reason }, State) ->
  { stop, Reason, State };
handle_info (_Msg, State) ->
  { noreply, State }.

terminate (_Reason, _State) ->
  ok.

code_change (_OldVsn, State, _Extra) ->
  { ok, State }.
